<?php
namespace ManagerX\Controller;
use Think\Controller;
class AjaxController extends Controller {
    public function ajax_login(){
		$post_data = get_json();
		if(isset($post_data['username']) && isset($post_data['password']) && isset($post_data['captcha'])){
			if(check_verify($post_data['captcha'])){
				$result = M('admin')->field('id,username,password,salt,role')->where(array('username'=>$post_data['username']))->find();
				if($result && $result['password'] === pwd_encrypt($post_data['password'] , $result['salt'])){
					session('user',  array('id'=>$result['id'], 'username'=>$result['username'], 'role'=>$result['role']));
					print_json(array('code' => 0, 'msg'=>'登录成功'));
				}else{
					print_json(array('code' => 2, 'msg'=>'用户名或密码错误'));
				}
			}else{
				print_json(array('code' => 2, 'msg'=>'验证码错误'));
			}
		}else{
			print_json(array('code' => 1, 'msg'=>'参数错误'));
		}
	}

	public function ajax_user_list(){
		if(session('?user') && session('user.role') == 1){
			$page = I('get.page');$limit = I('get.limit');$keyword = I('get.keyword');
			if($page > 0 && $limit > 0){
				$count = M('admin')
						->where(array('username' => array('LIKE', '%' . $keyword . '%')))
						->count();
                $result = M('admin')
                        ->field('id, username, phone , role')
						->where(array('username' => array('LIKE', '%' . $keyword . '%')))
                        ->limit(($page - 1) * $limit, $limit)
                        ->select();
				foreach ($result as $key => $value) {
					if(strlen($result[$key]['phone'] > 4)){
						$result[$key]['phone'] = '*******'.substr($result[$key]['phone'], -4);
					}
				}
                print_json(array('code' => 0, 'msg'=>'', 'count'=>$count, 'data'=>$result));
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_user_update(){
		if(session('?user')){
			$post_data = get_json();
			if(isset($post_data['id']) && isset($post_data['username']) && isset($post_data['password']) 
				&& isset($post_data['phone']) && isset($post_data['role'])){
				$user['username'] = $post_data['username'];
				$user['salt'] = GetRandStr(6);
				$user['password'] = pwd_encrypt($post_data['password'] , $user['salt']);
				$user['phone'] = $post_data['phone'];
				if(session('user.role') == 1){
					$user['role'] = $post_data['role'];
					if(M('admin')->where(array('id'=>$post_data['id']))->save($user)){
						print_json(array('code' => 0, 'msg'=>'修改成功'));
					}else{
						print_json(array('code' => 3, 'msg'=>'修改失败'));
					}
				}else{
					if(M('admin')->where(array('id'=>session('user.id')))->save($user)){
						print_json(array('code' => 0, 'msg'=>'修改成功'));
					}else{
						print_json(array('code' => 3, 'msg'=>'修改失败'));
					}
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_user_add(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['username']) && isset($post_data['password']) 
				&& isset($post_data['phone']) && isset($post_data['role'])){
				$user['username'] = $post_data['username'];
				$user['salt'] = GetRandStr(6);
				$user['password'] = pwd_encrypt($post_data['password'] , $user['salt']);
				$user['phone'] = $post_data['phone'];
				$user['role'] = $post_data['role'];
				if(M('admin')->data($user)->add()){
					print_json(array('code' => 0, 'msg'=>'添加成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'添加失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_user_delete(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['id'])){
				if(M('admin')->where(array('id'=>$post_data['id']))->delete()){
					print_json(array('code' => 0, 'msg'=>'删除成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'删除失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_config_update(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['title']) && isset($post_data['version']) && isset($post_data['callback']) && isset($post_data['getscript'])){
				$result = M('config')->where(array('name'=>'title'))->save(array('value'=>$post_data['title']));
				$result = M('config')->where(array('name'=>'ver'))->save(array('value'=>$post_data['version'])) || $result;
				$result = M('config')->where(array('name'=>'callback'))->save(array('value'=>$post_data['callback'])) || $result;
				$result = M('config')->where(array('name'=>'getscript'))->save(array('value'=>$post_data['getscript'])) || $result;
				$result = M('config')->where(array('name'=>'sms_user'))->save(array('value'=>$post_data['sms_user'])) || $result;
				$result = M('config')->where(array('name'=>'sms_pass'))->save(array('value'=>$post_data['sms_pass'])) || $result;
				if($result){
					print_json(array('code' => 0, 'msg'=>'修改成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'修改失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_payload_list(){
		if(session('?user') && session('user.role') == 1){
			$page = I('get.page');$limit = I('get.limit');$keyword = I('get.keyword');
			if($page > 0 && $limit > 0){
				$count = M('payload')
						->where(array('name' => array('LIKE', '%' . $keyword . '%')))
						->count();
                $result = M('payload')
                        ->field('id, name, desc ,key , time')
						->where(array('name' => array('LIKE', '%' . $keyword . '%')))
                        ->limit(($page - 1) * $limit, $limit)
                        ->select();
                print_json(array('code' => 0, 'msg'=>'', 'count'=>$count, 'data'=>$result));
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_payload_delete(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['id'])){
				if(M('payload')->where(array('id'=>$post_data['id']))->delete()){
					print_json(array('code' => 0, 'msg'=>'删除成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'删除失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_payload_add(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['name']) && isset($post_data['payload'])){
				if(M('payload')->where(array('key'=>$post_data['key']))->find()){
					print_json(array('code' => 3, 'msg'=>'字段名重复'));
				}else{					
					$payload['name'] = $post_data['name'];
					$payload['key'] = $post_data['key'];
					$payload['payload'] = $post_data['payload'];
					$payload['desc'] = $post_data['desc'];
					$payload['time'] = time();
					if(M('payload')->data($payload)->add()){
						print_json(array('code' => 0, 'msg'=>'添加成功'));
					}else{
						print_json(array('code' => 3, 'msg'=>'添加失败'));
					}
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_payload_update(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['id']) && isset($post_data['name']) && isset($post_data['key']) && isset($post_data['payload'])){
				$payload['name'] = $post_data['name'];
				$payload['key'] = $post_data['key'];
				$payload['payload'] = $post_data['payload'];
				$payload['desc'] = $post_data['desc'];
				if(M('payload')->where(array('id'=>$post_data['id']))->save($payload)){
					print_json(array('code' => 0, 'msg'=>'修改成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'修改失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_template_list(){
		if(session('?user') && session('user.role') == 1){
			$page = I('get.page');$limit = I('get.limit');$keyword = I('get.keyword');
			if($page > 0 && $limit > 0){
				$count = M('template')
						->where(array('name' => array('LIKE', '%' . $keyword . '%')))
						->count();
                $result = M('template')
                        ->field('id, name, desc, time')
						->where(array('name' => array('LIKE', '%' . $keyword . '%')))
                        ->limit(($page - 1) * $limit, $limit)
                        ->select();
				print_json(array('code' => 0, 'msg'=>'', 'count'=>$count,'data'=>$result));
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_template_delete(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['id'])){
				if(M('template')->where(array('id'=>$post_data['id']))->delete()){
					print_json(array('code' => 0, 'msg'=>'删除成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'删除失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_template_update(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['id'])){
				if(M('template')->where(array('id'=>$post_data['id']))->save(array('name'=>$post_data['name'], 'desc'=>$post_data['desc'], 'script'=>$post_data['script']))){
					print_json(array('code' => 0, 'msg'=>'修改成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'修改失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_template_add(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['name'])){
				if(M('template')->data(array('name'=>$post_data['name'], 
												'desc'=>$post_data['desc'], 
												'script'=>$post_data['script'],
												'time'=>time()))->add()){
					print_json(array('code' => 0, 'msg'=>'添加成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'添加失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	/*
	public function ajax_project_enable(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['id'])){
				//先设置所有模板为禁用
				M('template')->where(array('enabled'=>1))->save(array('enabled'=>0));
				// 再启用选择的模板
				if(M('template')->where(array('id'=>$post_data['id']))->save(array('enabled'=>1))){
					print_json(array('code' => 0, 'msg'=>'启用成功'));
				}else{
					print_json(array('code' => 1, 'msg'=>'启用失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}
	*/

	public function ajax_project_list(){
		if(session('?user')){
			$page = I('get.page');$limit = I('get.limit');$keyword = I('get.keyword');
			if($page > 0 && $limit > 0){
				$count = session('user.role') == 1 ? 
						(M('project')
						->join('admin on project.user_id = admin.id', 'left')
						->where(array('project.name' => array('LIKE', '%' . $keyword . '%')))
						->count()) :
						(M('project')
						->join('admin on project.user_id = admin.id', 'left')
						->where(array('project.name' => array('LIKE', '%' . $keyword . '%'), 'project.user_id'=>session('user.id')))
						->count());
				$result = session('user')['role'] == 1 ? 
						(M('project')
						->join('admin on project.user_id = admin.id', 'left')
						->join('template on project.template = template.id', 'left')
                        ->field('project.id, project.name, project.desc , admin.username, project.sms, payload, template.name as template, project.time')
						->where(array('project.name' => array('LIKE', '%' . $keyword . '%')))
                        ->limit(($page - 1) * $limit, $limit)
						->order('time desc')
                        ->select()) :
						(M('project')
						->join('admin on project.user_id = admin.id', 'left')
                        ->join('template on project.template = template.id', 'left')
                        ->field('project.id, project.name, project.desc , admin.username, project.sms, payload, template.name as template, project.time')
						->where(array('project.name' => array('LIKE', '%' . $keyword . '%'), 'project.user_id'=>session('user.id')))
                        ->limit(($page - 1) * $limit, $limit)
						->order('time desc')
                        ->select());
				foreach ($result as $key => $value) {
					$dst_payload = array();
					$payloads = unserialize($value['payload']);
					foreach($payloads as $v){
						$res = M('payload')->where(array('id'=>$v))->find();
						array_push($dst_payload, $res['name']);
					}
					$result[$key]['payload'] = $dst_payload;
				}
                print_json(array('code' => 0, 'msg'=>'', 'count'=>$count, 'data'=>$result));
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_project_update(){
		if(session('?user')){
			$post_data = get_json();
			if(isset($post_data['id']) && isset($post_data['sms'])){
				$result = session('user.role') == 1 ?
					M('project')->where(array('id'=>$post_data['id']))->save(array('sms'=>$post_data['sms'])) :
					M('project')->where(array('user_id'=>session('user.id'), 'id'=>$post_data['id']))->save(array('sms'=>$post_data['sms']));
				if($result){
					print_json(array('code' => 0, 'msg'=>'修改成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'修改失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_project_delete(){
		if(session('?user')){
			$post_data = get_json();
			if(isset($post_data['id'])){
				$result = session('user.role')== 1 ?
					M('project')->where(array('id'=>$post_data['id']))->delete() :
					M('project')->where(array('id'=>$post_data['id'], 'user_id'=>session('user.id')))->delete();
				if($result){
					print_json(array('code' => 0, 'msg'=>'删除成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'删除失败或没有权限'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_project_data_list(){
		if(session('?user')){
			$page = I('get.page');$limit = I('get.limit');$keyword = I('get.keyword');$project_id = I('get.project_id');
			if($page > 0 && $limit > 0 && $project_id > 0){
				// 验证是否有查看权限
				$project = M('project')->where(array('id'=>$project_id))->find();
				if(session('user.role') == 2 && session('user.id') != $project['user_id']){
					print_json(array('code' => 2, 'msg'=>'无权限'));
				}else{
					$count = M('project_data')
								->where(array(array('data' => array('LIKE', '%' . $keyword . '%'),'header'=>array('LIKE', '%' . $keyword . '%'),'ip'=>array('LIKE', '%' . $keyword . '%'),'_logic'=>'or'),'project'=>$project_id))
								->count();
					$result = M('project_data')
								->field('id, project, header, data, ip, time')
								->where(array(array('data' => array('LIKE', '%' . $keyword . '%'),'header'=>array('LIKE', '%' . $keyword . '%'),'ip'=>array('LIKE', '%' . $keyword . '%'),'_logic'=>'or'),'project'=>$project_id))
								->order('time desc')
								->limit(($page - 1) * $limit, $limit)
								->select();
					print_json(array('code' => 0, 'msg'=>'', 'count'=>$count, 'data'=>$result));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或无权限'));
		}
	}

	public function ajax_project_add(){
		if(session('?user')){
			$post_data = get_json();
			if(isset($post_data['name']) && isset($post_data['sms']) && isset($post_data['template']) && isset($post_data['payload']) && !empty($post_data['payload'])){
				// 生成一个唯一的项目ID
				$max_num = 10000;	// 最大项目数量
				$cur_wrap = 0; 	//当前轮询次数
				$max_wrap = $max_num;	//最大轮询次数，建议为最大项目数量
				$id = 0;
				do{
					$id = mt_rand(1, $max_num);
					$cur_wrap ++;
				}while(M('project')->where(array('id'=>$id))->find() && $cur_wrap <= $max_wrap);
				if($cur_wrap <= $max_wrap){
					$project['id'] = $id;
					$project['name'] = $post_data['name'];
					$project['desc'] = $post_data['desc'];
					$project['sms'] = $post_data['sms'];
					$project['user_id'] = session('user.id');
					$project['payload'] = serialize($post_data['payload']);
					$project['template'] = $post_data['template'];
					$project['time'] = time();
					if(M('project')->data($project)->add()){
						print_json(array('code' => 0, 'msg'=>'新建成功'));
					}else{
						print_json(array('code' => 3, 'msg'=>'新建失败'));
					}
				}else{
					print_json(array('code' => 3, 'msg'=>'生成项目ID失败，请重试或检查数量是否达上限'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆'));
		}
	}

    public function ajax_project_data_deleteall(){
        if(session('?user')){
			$post_data = get_json();
			if(isset($post_data['project_id'])){
				// 验证是否有查看权限
				$project = M('project')->where(array('id'=>$post_data['project_id']))->find();
				if(session('user.role') == 2 && session('user.id') != $project['user_id']){
					print_json(array('code' => 2, 'msg'=>'无权限'));
				}else{
					if(M('project_data')->where(array('project'=>$post_data['project_id']))->delete()){
						print_json(array('code' => 0, 'msg'=>'清空成功'));
					}else{
						print_json(array('code' => 3, 'msg'=>'清空失败'));
					}	
				}			
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
        }else{
            print_json(array('code' => 2, 'msg'=>'尚未登陆'));
        }

    }

	public function ajax_notice_list(){
		if(session('?user')){
			$count = session('user.role') == 1 ? 
						M('notice')->where(array('user_id'=>session('user.id')))->count() : 
						M('notice')->count();
			$result = session('user.role') == 1 ? 
						M('notice')->join('project on project.id=notice.project_id','left')
									->field('notice.id, project.name as project, notice.text, notice.time, notice.readed')
									->order('notice.time desc')
									->select() : 
						M('notice')->join('project on project.id=notice.project_id','left')
									->field('notice.id, project.name as project, notice.text, notice.time, notice.readed')
									->where(array('notice.user_id'=>session('user.id')))
									->order('notice.time desc')
									->select();
			print_json(array('code' => 0, 'msg'=>'', 'count'=>$count, 'data'=>$result));
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆'));
		}
	}

	public function ajax_notice_edit(){
		if(session('?user')){
			$post_data = get_json();
			if(isset($post_data['id'])){
				if(session('user.role') == 1 ? 
						M('notice')->where(array('id'=>$post_data['id']))->save(array('readed'=>1)) : 
						M('notice')->where(array('id'=>$post_data['id'], 'user_id'=>session('user.id')))->save(array('readed'=>1))){
					print_json(array('code' => 0, 'msg'=>'修改成功'));
				}else{
					print_json(array('code' => 3, 'msg'=>'修改失败'));
				}
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
			
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆'));
		}
	}

	public function ajax_sms_test(){
		if(session('?user') && session('user.role') == 1){
			$post_data = get_json();
			if(isset($post_data['sms_user']) && isset($post_data['sms_pass'])){
				$user = M('admin')->where(array('id'=>session('user.id')))->find();
				$res = sms_method($post_data['sms_user'] , $post_data['sms_pass'] , $user['phone'] , '【XSSER通知】您的10000项目于'.date('y-m-d h:i:s',time()).'接收到一条新数据，请及时查收。');
				print_json(array('code' => 0, 'msg'=>$res));
			}else{
				print_json(array('code' => 1, 'msg'=>'参数错误'));
			}
		}else{
			print_json(array('code' => 2, 'msg'=>'尚未登陆或没有权限'));
		}
	}
}